﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace DateReminderApp
{
    public partial class MainForm : Form
    {
        private BindingList<Reminder> reminders;
        private Timer checkTimer;
        private string dataFile = "reminders.dat";

        public MainForm()
        {
            InitializeComponent();
            SetupDataGridView();
            LoadReminders();
            StartTimer();
            SetupEventHandlers();
        }

        private void SetupDataGridView()
        {
            // 配置DataGridView列
            dataGridView.AutoGenerateColumns = false;
            dataGridView.Columns.Clear();

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Title",
                HeaderText = "标题",
                Width = 150
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ReminderTime",
                HeaderText = "提醒时间",
                Width = 120,
                DefaultCellStyle = new DataGridViewCellStyle {
                    Format = "yyyy-MM-dd HH:mm",
                    NullValue = DateTime.Now.ToString("yyyy-MM-dd HH:mm")
                }
            }); ; ;

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "TimeUntilReminder",
                HeaderText = "剩余时间",
                Width = 100,
                DefaultCellStyle = new DataGridViewCellStyle { 
                    Format = @"hh\:mm\:ss",
                    NullValue = "00:00:00"
                }
            });

            dataGridView.Columns.Add(new DataGridViewCheckBoxColumn
            {
                DataPropertyName = "IsCompleted",
                HeaderText = "已完成",
                Width = 60
            });
        }

        private void SetupEventHandlers()
        {
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            btnComplete.Click += BtnComplete_Click;
            numInterval.ValueChanged += NumInterval_ValueChanged;
        }

        private void LoadReminders()
        {
            reminders = new BindingList<Reminder>();

            if (File.Exists(dataFile))
            {
                try
                {
                    using (FileStream fs = new FileStream(dataFile, FileMode.Open))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        var loadedReminders = (List<Reminder>)formatter.Deserialize(fs);
                        // 添加null检查
                        if (loadedReminders != null)
                        {
                            foreach (var reminder in loadedReminders)
                            {
                                if (reminder != null)
                                {
                                    // 确保属性不为null
                                    if (reminder.Title == null) reminder.Title = "未知提醒";
                                    if (reminder.Description == null) reminder.Description = "";

                                    reminders.Add(reminder);
                                }
                            }
                        }
                    }
                    dataGridView.DataSource = reminders;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"加载数据失败: {ex.Message}");
                    reminders = new BindingList<Reminder>();
                    dataGridView.DataSource = reminders;
                }
            }

            dataGridView.DataSource = reminders;
        }

        private void SaveReminders()
        {
            try
            {
                // 确保所有提醒对象都是有效的
                var validReminders = reminders.Where(r => r != null).ToList();
                using (FileStream fs = new FileStream(dataFile, FileMode.Create))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(fs, reminders.ToList());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存数据失败: {ex.Message}");
            }
        }

        private void StartTimer()
        {
            checkTimer = new Timer();
            checkTimer.Interval = (int)numInterval.Value * 1000;
            checkTimer.Tick += CheckTimer_Tick;
            checkTimer.Start();
        }

        private void CheckTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                // 检查数据源
                if (dataGridView.DataSource == null)
                {
                    Console.WriteLine("DataSource is null");
                    return;
                }

                if (reminders == null)
                {
                    Console.WriteLine("reminders is null");
                    return;
                }

                dataGridView.Refresh();

                // 添加null检查
                var dueReminders = reminders
                    .Where(r => r != null && !r.IsCompleted && r.ReminderTime <= DateTime.Now)
                    .ToList();

                foreach (var reminder in dueReminders)
                {
                    if (reminder != null)
                    {
                        ShowReminderAlert(reminder);
                        reminder.IsCompleted = true;
                    }
                }

                if (dueReminders.Any())
                {
                    SaveReminders();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CheckTimer_Tick error: {ex.Message}");
            }
        }

        private void ShowReminderAlert(Reminder reminder)
        {
            SystemSounds.Exclamation.Play();

            var alertForm = new Form
            {
                Text = "提醒通知",
                Size = new Size(400, 200),
                StartPosition = FormStartPosition.CenterScreen,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                MaximizeBox = false,
                MinimizeBox = false
            };

            var label = new Label
            {
                Text = $"⚠️ 提醒：{reminder.Title}\n\n时间：{reminder.ReminderTime:yyyy-MM-dd HH:mm}\n\n{reminder.Description}",
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleCenter,
                Font = new Font("Microsoft YaHei", 12)
            };

            var btnClose = new Button
            {
                Text = "知道了",
                Size = new Size(100, 30),
                Location = new Point(150, 120)
            };
            btnClose.Click += (s, e) => alertForm.Close();

            alertForm.Controls.Add(label);
            alertForm.Controls.Add(btnClose);
            alertForm.ShowDialog();
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {

            try
            {
                using (var form = new EditReminderForm())
                {
                    if (form.ShowDialog() == DialogResult.OK && form.Reminder != null)
                    {
                        reminders.Add(form.Reminder);
                        SaveReminders();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加提醒失败: {ex.Message}");
            }
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                var selectedReminder = dataGridView.SelectedRows[0].DataBoundItem as Reminder;
                using (var form = new EditReminderForm(selectedReminder))
                {
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        dataGridView.Refresh();
                        SaveReminders();
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择一个提醒");
            }
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                if (MessageBox.Show("确定要删除这个提醒吗？", "确认删除",
                    MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    var selectedReminder = dataGridView.SelectedRows[0].DataBoundItem as Reminder;
                    reminders.Remove(selectedReminder);
                    SaveReminders();
                }
            }
            else
            {
                MessageBox.Show("请先选择一个提醒");
            }
        }

        private void BtnComplete_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                var selectedReminder = dataGridView.SelectedRows[0].DataBoundItem as Reminder;
                selectedReminder.IsCompleted = !selectedReminder.IsCompleted;
                dataGridView.Refresh();
                SaveReminders();
            }
            else
            {
                MessageBox.Show("请先选择一个提醒");
            }
        }

        private void NumInterval_ValueChanged(object sender, EventArgs e)
        {
            if (checkTimer != null)
            {
                checkTimer.Interval = (int)numInterval.Value * 1000;
            }
        }

        // 添加缺失的 MainForm_Load 方法
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 确保所有对象都已初始化
                if (reminders == null)
                {
                    reminders = new BindingList<Reminder>();
                    dataGridView.DataSource = reminders;
                }

                if (checkTimer == null)
                {
                    StartTimer();
                }

                this.Text = $"日期提醒小助手 - 已加载 {reminders.Count} 个提醒";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"窗体加载错误: {ex.Message}");
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            checkTimer?.Stop();
            SaveReminders();
            base.OnFormClosing(e);
        }

        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}